package com.archeanx.lib.http;

import android.support.annotation.NonNull;
import android.util.Log;


import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @创建者
 * @创建时间
 * @描述 设置用户代理拦截器（User-Agent Interceptor）  修改head
 * todo 添加了通用的头部
 */
public class XUserAgentInterceptor implements Interceptor {
    private static final String USER_AGENT_HEADER_NAME = "User-Agent";
    private final String userAgentHeaderValue;

    public XUserAgentInterceptor(@NonNull String userAgentHeaderValue) {
        this.userAgentHeaderValue = userAgentHeaderValue;
    }

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        //老毕服务器需要加的头部
        String timeMillis = Long.toString(System.currentTimeMillis());
        String filpTime=new StringBuffer(timeMillis).reverse().toString();

        final Request originalRequest = chain.request();
        final Request requestWithUserAgent = originalRequest.newBuilder()
                .removeHeader(USER_AGENT_HEADER_NAME)
                .addHeader(USER_AGENT_HEADER_NAME, userAgentHeaderValue)
                .addHeader("t",timeMillis)
                .addHeader("k",filpTime)
                .build();
        return chain.proceed(requestWithUserAgent);
    }


    /**
     * 返回正确的UserAgent
     */
    public static String getUserAgent() {
        String userAgent = "";
        StringBuffer sb = new StringBuffer();
        try {
            userAgent = System.getProperty("http.agent");//Dalvik/2.1.0 (Linux; U; Android 6.0.1; vivo X9L Build/MMB29M)

            for (int i = 0, length = userAgent.length(); i < length; i++) {
                char c = userAgent.charAt(i);
                if (c <= '\u001f' || c >= '\u007f') {
                    sb.append(String.format("\\u%04x", (int) c));
                } else {
                    sb.append(c);
                }
            }

            Log.v("User-Agent", "User-Agent: " + sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}

